using System;
using System.ComponentModel;
using System.Net;
using System.Web;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace wParser
{
  public partial class TestForm : Form
  {
    private MySqlConnection conn;
    private const string m_weatherTableName = "sl_weather";
    private const string m_url = "http://pogoda.open.by/minsk/detail";

    public TestForm()
    {
      InitializeComponent();
      Closing += delegate { if (conn != null) conn.Close(); };
    }

    private void TestForm_Load(object sender, EventArgs e)
    {
      webBrowser1.DocumentText = "Loading document...";
    }

    protected override void OnShown(EventArgs e)
    {
      base.OnShown(e);
      try
      {
        string weatherData = ParseWeatherData(m_url, true);
        Connect();
        InsertData(weatherData);
        webBrowser1.DocumentText = weatherData;
      }
      catch(Exception ex)
      {
        webBrowser1.DocumentText = ex.Message; 
      }
    }

    private static string ParseWeatherData(string url, bool encode)
    {
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
      WebResponse response = request.GetResponse();

      string parsed = OpenByParser.Parse(response.GetResponseStream());
      
      return encode ? HttpUtility.HtmlEncode(parsed) : parsed;
    }

    private void Connect()
    {
      string connStr = String.Format("server={0};user id={1}; password={2}; database=weather; pooling=false; charset=utf8",
          "10.220.1.101", "weather", "0slo");

      try
      {
        conn = new MySqlConnection(connStr);
        conn.Open();
      }
      catch (MySqlException ex)
      {
        webBrowser1.DocumentText = ex.Message;
      }
    }

    private void InsertData(string weatherData)
    {
      const string truncateText = "TRUNCATE TABLE " + m_weatherTableName;
      string insertText = string.Format("INSERT INTO {0} (`weatherData`) VALUES ('{1}');",
                                        m_weatherTableName, weatherData);

      MySqlHelper.ExecuteScalar(conn, truncateText);
      MySqlHelper.ExecuteScalar(conn, insertText);
    }

  }
}